package cn.cds.withyou.admin.ui.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.squareup.otto.Subscribe;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cds.withyou.admin.Application;
import cn.cds.withyou.admin.R;
import cn.cds.withyou.admin.actions.ActionsCreator;
import cn.cds.withyou.admin.stores.ActivityStore;
import cn.cds.withyou.admin.ui.widget.CommonTitleBar;
import cn.cds.withyou.lib.model.ActivityDto;
import cn.ljs.android.buses.ActionBus;
import cn.ljs.android.buses.DataBus;
import cn.ljs.android.ui.BaseActivity;
import cn.ljs.android.util.AppUtils;
import cn.ljs.android.util.TUtil;

/**
 * <p> Description: </p>
 * <p/>
 * <p> Copyright: Copyright (c) 2016 </p>
 *
 * @author: Json.Lee
 * @Version: 1.0
 * @CreateTime: 8/5/2016 12:22
 */
public class ActivityAddedActivity extends BaseActivity {

    @Bind(R.id.title_et)
    EditText titleEt;
    @Bind(R.id.date_et)
    EditText dateEt;
    @Bind(R.id.start_time_et)
    EditText startTimeEt;
    @Bind(R.id.end_time_et)
    EditText endTimeEt;
    @Bind(R.id.address_et)
    EditText addressEt;
    @Bind(R.id.course_pic_et)
    EditText coursePicEt;
    @Bind(R.id.comment_et)
    EditText commentEt;
    @Bind(R.id.content_scroll)
    ScrollView contentScroll;

    private ActionsCreator mCreator;
    private ActionBus mActionBus;
    private DataBus mDataBus;
    private ActivityStore mStore;

    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
    private final static SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        DATE_FORMAT.setTimeZone(TimeZone.getDefault());
        TIME_FORMAT.setTimeZone(TimeZone.getDefault());
        DATE_TIME_FORMAT.setTimeZone(TimeZone.getDefault());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_added);
        ButterKnife.bind(this);

        init();
    }

    private void init() {
        contentScroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AppUtils.hideKeyBoard(ActivityAddedActivity.this);
                return false;
            }
        });

        mCreator = ActionsCreator.get();
        mActionBus = Application.getInstance().getActionsBus();
        mDataBus = Application.getInstance().getDataBus();
        mStore = ActivityStore.get();

        mDataBus.register(this);
        mActionBus.register(mStore);
    }

    @Override
    protected void onDestroy() {
        mActionBus.unregister(mStore);
        mDataBus.unregister(this);
        super.onDestroy();
    }

    @OnClick({R.id.add_btn, R.id.date_et, R.id.start_time_et, R.id.end_time_et})
    public void onClick(View view) {
        switch (view.getId()) {
            case CommonTitleBar.LEFT_BUTTON_ID:
                finish();
                break;
            case R.id.add_btn:
                AppUtils.hideKeyBoard(this);
                ActivityDto act = getParams();
                if (checkParams(act)) {
                    mCreator.requestActivityAdded(act);
                }
                break;
            case R.id.date_et:
                AppUtils.hideKeyBoard(this);
                showDate();
                break;
            case R.id.start_time_et:
                AppUtils.hideKeyBoard(this);
                showTime(startTimeEt);
                break;
            case R.id.end_time_et:
                AppUtils.hideKeyBoard(this);
                showTime(endTimeEt);
                break;
            default:
                return;
        }
    }

    private void showTime(final TextView v) {
        Calendar current = Calendar.getInstance();
        if (!TextUtils.isEmpty(v.getText().toString().trim())) {
            try {
                current.setTime(TIME_FORMAT.parse(v.getText().toString().trim()));
            } catch (ParseException e) {
            }
        }
        TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                v.setText(String.format("%02d:%02d:00", hourOfDay, minute));
            }
        }, current.get(Calendar.HOUR_OF_DAY), current.get(Calendar.MINUTE), true);
        dialog.show();
    }

    private void showDate() {
        Calendar current = Calendar.getInstance();
        if (!TextUtils.isEmpty(dateEt.getText().toString().trim())) {
            try {
                current.setTime(DATE_FORMAT.parse(dateEt.getText().toString().trim()));
            } catch (ParseException e) {
            }
        }
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar date = Calendar.getInstance();
                date.set(year, monthOfYear, dayOfMonth);
                dateEt.setText(DATE_FORMAT.format(date.getTime()));
            }
        }, current.get(Calendar.YEAR), current.get(Calendar.MONTH), current.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    private boolean checkParams(ActivityDto act) {
        if (TextUtils.isEmpty(act.getActivityName())) {
            TUtil.shortToast("请输入活动标题。");
            return false;
        }
        if (act.getActivityStartT() < 0 && act.getActivityEndT() < 0) {
            TUtil.shortToast("请选择活动日期。");
            return false;
        }
        if (act.getActivityStartT() == 0) {
            TUtil.shortToast("请选择活动开始时间。");
            return false;
        }
        if (act.getActivityEndT() == 0) {
            TUtil.shortToast("请选择活动结束时间。");
            return false;
        }
        if (act.getActivityStartT() <= System.currentTimeMillis()) {
            TUtil.shortToast("开始时间需大于当前时间。");
            return false;
        }
        if (act.getActivityEndT() <= act.getActivityStartT()) {
            TUtil.shortToast("结束时间应大于开始时间。");
            return false;
        }
        if (TextUtils.isEmpty(act.getActivityAddress())) {
            TUtil.shortToast("请选择活动地址。");
            return false;
        }
        if (TextUtils.isEmpty(act.getActivityPic())) {
            TUtil.shortToast("请输入活动图片链接。");
            return false;
        }
        if (TextUtils.isEmpty(act.getActivityContent())) {
            TUtil.shortToast("请输入活动备注。");
            return false;
        }
        return true;
    }

    @Subscribe
    public void updateUI(ActivityStore.ActivityEvent event) {
        switch (event.code) {
            case ActivityStore.ActivityEvent.ACTIVITY_ADD_SUCC:
                TUtil.shortToast("添加成功。");
                finish();
                break;
            case ActivityStore.ActivityEvent.ACTIVITY_ADD_FAIL:
                TUtil.shortToast("添加失败，请重试。");
                break;
            default:
                return;
        }
    }

    private ActivityDto getParams() {
        ActivityDto act = new ActivityDto();
        act.setActivityName(titleEt.getText().toString().trim());
        if (!TextUtils.isEmpty(dateEt.getText().toString().trim())) {
            if (!TextUtils.isEmpty(startTimeEt.getText().toString().trim())) {
                try {
                    Date startT = DATE_TIME_FORMAT.parse(TextUtils.concat(dateEt.getText().toString().trim(), " ", startTimeEt.getText().toString().trim()).toString());
                    act.setActivityStartT(startT.getTime());
                } catch (ParseException e) {
                    act.setActivityStartT(0);
                }
            }
            if (!TextUtils.isEmpty(endTimeEt.getText().toString().toString())) {
                try {
                    Date endT = DATE_TIME_FORMAT.parse(TextUtils.concat(dateEt.getText().toString().trim(), " ", endTimeEt.getText().toString().trim()).toString());
                    act.setActivityEndT(endT.getTime());
                } catch (ParseException e) {
                    act.setActivityEndT(0);
                }
            }
        } else {
            act.setActivityStartT(-1);
            act.setActivityEndT(-1);
        }
        act.setActivityAddress(addressEt.getText().toString().trim());
        act.setActivityPic(coursePicEt.getText().toString().trim());
        act.setActivityContent(commentEt.getText().toString().trim());
        return act;
    }
}
